package cn.lyjuan.dwz_manage.core.config;

import cn.lyjuan.dwz_manage.core.base.pojo.ActionPojo;
import cn.lyjuan.dwz_manage.core.base.pojo.ManagePojo;
import cn.lyjuan.dwz_manage.core.java.cst.TypeCst;
import cn.lyjuan.dwz_manage.core.java.mapper.IMgManageMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chad on 2016/8/23.
 * 为独立SQL代码，启用该服务
 */
public class UserDetailsServiceImpl implements UserDetailsService
{
    private IMgManageMapper mgManageMapper;

    public UserDetailsServiceImpl(IMgManageMapper mgManageMapper)
    {
        this.mgManageMapper = mgManageMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        // 查找用户
        ManagePojo manage = mgManageMapper.selectByName(username);

        if (null == manage)
            throw new UsernameNotFoundException("用户名或密码错误");

        // 查找权限
        List<GrantedAuthority> auths = null;


        List<ActionPojo> actions = mgManageMapper.selectPrivilegeByManageId(manage.getId());

        auths = new ArrayList<>(actions.size());
        for (ActionPojo a : actions)
            auths.add(new SimpleGrantedAuthority(a.getActionurl()));

        return new User(username, manage.getPwd(), manage.getStatus() == TypeCst.Status.OK, true, true, true, auths);
    }
}
